package com.smartystars.quizzer;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.Map;
import java.util.Random;


import com.smartystars.quizzerServer.DownloadableQuestions;
import com.smartystars.quizzerServer.ExternalStorage;
import com.smartystars.quizzerServer.Question;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;


/**
 * 
 * @author Dominik v.d.Heydt
 * 
 */
public class SingleplayerActivity extends Activity {

	private DownloadableQuestions allQuestions;
	private ArrayList<Question> themedQuestions;
	private ArrayList<String> themes;
	private int questionCounter = 1;
	private ImageButton answer1;
	private ImageButton answer2;
	private ImageButton answer3;
	private TextView kategorie;
	private TextView frage;
	private TextView txtAnswer1;
	private TextView txtAnswer2;
	private TextView txtAnswer3;
	private TextView txtScore;
	private TextView txtTime;
	private short answer = 0;
	private Question currentQuestion;
	private int score = 0;
	private int streak = 0;
	private Handler UIhandler = new Handler();
	private Handler timerHandler = new Handler();
	private short time = 30;
	private boolean gameRunning = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.singleplayer_layout);

		Map<String, File> externalLocations = ExternalStorage
				.getAllStorageLocations();
		File sdCard = externalLocations.get(ExternalStorage.SD_CARD);

		ObjectInputStream ois = null;
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(sdCard + "/Quizzer/questions.ser");
			ois = new ObjectInputStream(fis);
			Object obj = ois.readObject();
			if (obj instanceof DownloadableQuestions) {
				allQuestions = (DownloadableQuestions) obj;

			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

		answer1 = (ImageButton) findViewById(R.id.btnAnswer1);
		answer2 = (ImageButton) findViewById(R.id.btnAnswer2);
		answer3 = (ImageButton) findViewById(R.id.btnAnswer3);
		frage = (TextView) findViewById(R.id.txtfrage);
		kategorie = (TextView) findViewById(R.id.txtkategorie);
		txtAnswer1 = (TextView) findViewById(R.id.txtbtnAnswer1);
		txtAnswer2 = (TextView) findViewById(R.id.txtbtnAnswer2);
		txtAnswer3 = (TextView) findViewById(R.id.txtbtnAnswer3);
		txtScore = (TextView) findViewById(R.id.txtScore);
		txtTime = (TextView) findViewById(R.id.txtTime);

		answer1.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				answer = 1;
				answerHandler();

			}
		});

		answer2.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				answer = 2;
				answerHandler();

			}
		});

		answer3.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				answer = 3;
				answerHandler();

			}
		});
		setupSingleplayer();
	}

	private void setupSingleplayer() {
		themes = allQuestions.getThemes();
		System.out.println("OverallThemes: " + themes.size());
		themedQuestions = allQuestions.getThemedQuestions(getRandomTheme());

		currentQuestion = getRandomQuestion();

		System.out.println("SetupSIngleplayer");

		setNewQuestion();
		startTimer();
		gameRunning = true;

	}

	private String getRandomTheme() {
		System.out.println("getRandomTheme size: " + themes.size());

		System.out.println("random theme");

		Random rand = new Random();

		if (themes.size() != 0) {
			int index = rand.nextInt(themes.size());
			String theme = themes.get(index);
			themes.remove(index);
			System.out.println(theme);
			return theme;
		} else {
			return "";
		}

	}

	private Question getRandomQuestion() {
		Random rand = new Random();

		System.out.println("Themed Size: " + themedQuestions.size());
		int index = rand.nextInt(themedQuestions.size());
		Question ques = themedQuestions.get(index);
		themedQuestions.remove(index);

		return ques;
	}

	private void setNewQuestion() {
		System.out.println("set New Question");

		UIhandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				kategorie.setText((CharSequence) currentQuestion.getKey());
				frage.setText((CharSequence) currentQuestion.getValue());
				ArrayList<String> answeres = currentQuestion.getAnsweres();

				txtAnswer1.setText(answeres.get(0));
				txtAnswer2.setText(answeres.get(1));
				txtAnswer3.setText(answeres.get(2));
			}
		}, 100);
	}

	private void startTimer() {
		timerHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				if (time != 0) {

					time -= 1;
					txtScore.setText("Score: " +String.valueOf(score));
					txtTime.setText("Time: " + String.valueOf(time));
					if (gameRunning) {

						startTimer();
					}
				} else {
					finishedGame();
				}
			}
		}, 1000);
	}

	private void answerHandler() {
		System.out.println("Answer Handler");

		if (answer == currentQuestion.getSolution()) {
			score = score + 10 + streak;
			streak = streak + 10;
		} else {
			streak = 0;
		}

		questionCounter++;

		if ((questionCounter % 5) != 0) {
			if (themedQuestions.size() == 0) {
				themedQuestions = allQuestions
						.getThemedQuestions(getRandomTheme());
				if (themedQuestions.size() != 0) {
					questionCounter = 1;
					currentQuestion = getRandomQuestion();
					setNewQuestion();
				} else {
					finishedGame();
				}
			} else {
				currentQuestion = getRandomQuestion();
				setNewQuestion();
			}
		} else {
			if (themedQuestions.size() == 0) {
				themedQuestions = allQuestions
						.getThemedQuestions(getRandomTheme());
				if (themedQuestions.size() != 0) {
					questionCounter = 1;
					currentQuestion = getRandomQuestion();
					setNewQuestion();
				} else {
					finishedGame();
				}
			} else {
				questionCounter = 1;
				themedQuestions = allQuestions
						.getThemedQuestions(getRandomTheme());
				currentQuestion = getRandomQuestion();
				setNewQuestion();
			}
		}

	}

	private void finishedGame() {
		gameRunning = false;
		AlertDialog.Builder finishedDialog = new AlertDialog.Builder(this);
		finishedDialog.setTitle("Singleplayer game finished");
		finishedDialog
				.setMessage("No more questions found you finished the game with: "
						+ score + "points.");
		finishedDialog.setPositiveButton("Back",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						SingleplayerActivity.this.finish();
						Intent myIntent = new Intent(getBaseContext(),
								QuizzerStartupActivity.class);
						myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						startActivity(myIntent);

					}
				});
		finishedDialog.setCancelable(false);
		finishedDialog.show();
	}

	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if (keyCode == KeyEvent.KEYCODE_BACK) {
	    	gameRunning = false;
	    	
	        finish();
	        return true;
	    }
	    return super.onKeyDown(keyCode, event);
	}
}
